package com.txm.service;

import com.txm.qqcommon.File_;
import com.txm.qqcommon.Message;

import java.io.File;
import java.io.FileOutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* 接收文件
* */
public class ReceiveFile {
    static String filePath;
    static FileOutputStream fos = null;
    static {
        URI uri = null;
        try {
            uri = ReceiveFile.class.getResource("/").toURI();
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
        Path path = Paths.get(uri).getParent().getParent().getParent();
        filePath = path.toString();
        System.out.println("filePath:" + filePath);
    }

    public static void handleReceiveFile(Message msg) {
        try {
            File_ file_info = (File_) msg.getObject();

            File file = new File(filePath + "\\receiveFile\\" + msg.getSender());
            if (!file.exists()) {
                if (!file.mkdirs()) System.out.println("文件夹创建失败。");
            } else {
//                System.out.println("文件夹已存在。");
            }
            File file1 = new File(file, file_info.getFileName());
            if (!file1.createNewFile()) {
//                System.out.println("文件已存在。");
            }

            if (file_info.getStatus() == 0) {
                fos = new FileOutputStream(file1);
            }

            fos.write(file_info.getDataCut(), 0, Long.valueOf(file_info.getDataCut_size()).intValue());
            file_info.getProgress();

            if (file_info.getStatus() == -1) {
                fos.close();
                System.out.println("文件已存入：" + file1.getAbsolutePath());
            }
        } catch (Exception e) {
            System.out.println("handleReceiveFile Exception:" + e);
        }
    }
}
